<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Gass_users_model extends CI_Model {
	
	// The following method prevents an error occurring when $this->data is modified.
	// Error Message: 'Indirect modification of overloaded property Demo_cart_admin_model::$data has no effect'.
	public function &__get($key)
	{
		$CI =& get_instance();
		return $CI->$key;
	}
	###++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###	
	// User Accounts
	###++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###	

 	/**
	 * get_user_accounts
	 * Gets a paginated list of users that can be filtered via the user search form, filtering by the users email and first and last names.
	 */
	function get_user_accounts()
	{
    $uri = $this->uri->uri_to_assoc(3);
    $limit = $this->config->item('pag_limit');
		$offset = (isset($uri['page'])) ? $uri['page'] : FALSE;
				
		if (array_key_exists('search_key_words', $uri))
		{
			$pagination_url = 'gass_auth_teachers/manage_user_accounts/search_key_words/'.$uri['search_key_words'].'/select_u_group/'.$uri['select_u_group'].'/';
			$config['uri_segment'] = 8; // Changing to 6 will select the 6th segment, example 'controller/function/search/query/page/10'.
	    
	    $search_key_words = str_replace('-',' ',urldecode($uri['search_key_words']));
	    $select_u_group = str_replace('-',' ',urldecode($uri['select_u_group']));
			
      $this->db->select('*');
      $this->db->from('userlistview');
      $where = '';
      
      if ($select_u_group!='all'){
      	$where = "ugrp_id = ".$select_u_group;
      }else{
      	$where = "ugrp_id != 10";
      }
      
      if ($search_key_words!='0000'){
      	$where = $where." and ( uacc_username like '%".$search_key_words."%' or uacc_email like '%".$search_key_words."%' )";
      }      
      
      
      
      
      //$where = "uacc_username like '%".$search_key_words."%' or uacc_email like '%".$search_key_words."%' ";
      $this->db->where($where);
      $this->db->limit($limit, $offset);
      $query =$this->db->get();

      $this->db->select('*');
      $this->db->from('userlistview');
      $this->db->where($where);   
			$total_users = $this->db->get()->num_rows();			

			$this->data['users'] = $query->result_array();				
			
		}
		else
		{
	  	$search_key_words	='';
	  	$select_u_group	='';
			$pagination_url = 'gass_auth_teachers/manage_user_accounts/';
			$search_query = FALSE;
			$config['uri_segment'] = 4; // Changing to 4 will select the 4th segment, example 'controller/function/page/10'.
			
      $this->db->select('*');
      $this->db->from('userlistview');
      $this->db->limit($limit, $offset);
      $query =$this->db->get();
			$total_users = $this->db->get('userlistview')->num_rows();			
			
			$this->data['users'] = $query->result_array();				

		}
		
		// Create user record pagination.
		$this->load->library('pagination');	
		$config['base_url'] = base_url().$pagination_url.'page/';
		$config['total_rows'] = $total_users;
		$config['per_page'] = $limit; 

		$this->pagination->initialize($config); 
		$this->data['search_key_words'] = ($search_key_words!='0000')?$search_key_words:''; // Populates search input field in view.
		$this->data['select_u_group'] = $select_u_group; 		
		// Make search query and pagination data available to view.
		//$this->data['search_query'] = $search_query; // Populates search input field in view.
		$this->data['pagination']['links'] = $this->pagination->create_links();
		$this->data['pagination']['total_users'] = $total_users;
	}
	
  /**
	 * manage_user_groups
	 * The function loops through all POST data checking the 'Delete' checkboxes that have been checked, and deletes the associated user groups.
	 */
  function manage_user_groups(){
		// Delete groups.
		if ($delete_groups = $this->input->post('delete_group')){
			foreach($delete_groups as $group_id => $delete)
			{
				// Note: As the 'delete_group' input is a checkbox, it will only be present in the $_POST data if it has been checked,
				// therefore we don't need to check the submitted value.
				$this->flexi_auth->delete_group($group_id);
			}
		}

		// Save any public or admin status or error messages to CI's flash session data.
		$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
		
		// Redirect user.
		redirect('gass_auth_teachers/manage_user_groups');			
	}
	
	###++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###	
	// Privileges
	###++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###	
	
  	/**
	 * update_privilege
	 * Updates a specific privilege.
	 */
	function update_privilege($privilege_id)
	{
		$this->load->library('form_validation');

		// Set validation rules.
		$validation_rules = array(
			array('field' => 'update_privilege_name', 'label' => 'Privilege Name', 'rules' => 'required')
		);
		
		$this->form_validation->set_rules($validation_rules);
		
		if ($this->form_validation->run())
		{
			// Get privilege data from input.
			$data = array(
				$this->flexi_auth->db_column('user_privileges', 'name') => $this->input->post('update_privilege_name'),
				$this->flexi_auth->db_column('user_privileges', 'description') => $this->input->post('update_privilege_description')
			);			

			$this->flexi_auth->update_privilege($privilege_id, $data);
				
			// Save any public or admin status or error messages to CI's flash session data.
			$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
			
			// Redirect user.
			redirect('gass_auth_teachers/manage_privileges');			
		}
	}
	
 	/**
	 * update_user_accounts
	 * The function loops through all POST data checking the 'Suspend' and 'Delete' checkboxes that have been checked, and updates/deletes the user accounts accordingly.
	 */
	function update_user_accounts()
    {
		// If user has privileges, delete users.
		//if ($this->flexi_auth->is_privileged('Delete Users')) 
		//{
			if ($delete_users = $this->input->post('delete_user'))
            {
                var_dump($this->input->post('delete_user'));
				foreach($delete_users as $user_id => $delete)
				{
					// Note: As the 'delete_user' input is a checkbox, it will only be present in the $_POST data if it has been checked,
					// therefore we don't need to check the submitted value.
					/*
					$this->db->trans_start();	
					$this->db->delete('ga_user_profiles', array('upro_id' => $user_id)); 
					$this->db->delete('user_accounts', array('uacc_id' => $user_id));
					$this->db->trans_complete();
					*/
					$this->flexi_auth->delete_user($user_id);
				}
			}
		//}
			
		// Update User Suspension Status.
		// Suspending a user prevents them from logging into their account.
		if ($user_status = $this->input->post('suspend_status'))
		{
			// Get current statuses to check if submitted status has changed.
			$current_status = $this->input->post('current_status');
			
			foreach($user_status as $user_id => $status)
			{
				if ($current_status[$user_id] != $status)
				{
					if ($status == 1)
					{
						$this->flexi_auth->update_user($user_id, array($this->flexi_auth->db_column('user_acc', 'suspend') => 1));
					}
					else
					{
						$this->flexi_auth->update_user($user_id, array($this->flexi_auth->db_column('user_acc', 'suspend') => 0));
					}
				}
			}
		}
		// Save any public or admin status or error messages to CI's flash session data.
		$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
		// Redirect user.
		redirect('gass_auth_teachers/manage_user_accounts');			
	}	
 	/**
	 * 更新用户的基本信息
	 * 
	 * 主要用于更新客户的角色信息、所属学院等信息
	 * 当客户角色为分院招生老师时，就必须指定所属分院
	 */
	function update_user_account()
  {
	 $this->load->library('form_validation');
	 $validation_rules = array(
			array('field' => 'upro_first_name', 'label' => '姓', 'rules' => 'required'),
			array('field' => 'upro_last_name', 'label' => '名', 'rules' => 'required'),
			array('field' => 'upro_phone', 'label' => '手机号码', 'rules' => 'required'),
			array('field' => 'upro_group', 'label' => '角色', 'rules' => 'required')
	 );
	 //当Email信息如果被改动，则要去判断是否在当前数据库中存在这个Email信息
	 if( $this->input->post('upro_email') != $this->input->post('original_email') )
	 {
	 	$validation_rules[] = array('field' => 'upro_email', 'label' => '邮箱', 'rules' => 'required|is_unique[user_accounts.uacc_email]');
	 }	 
	 else
	 {
	 	$validation_rules[] = array('field' => 'upro_email', 'label' => '邮箱', 'rules' => 'required');
	 }
	 
	 
	 
	 if($this->input->post('upro_group')==2)
	 {
	 	//当所属学院信息如果被改动，则要去判断是否在当前数据库中存在这个所属学院信息
	  if( $this->input->post('upro_college') != $this->input->post('original_upro_college') )
	  {
	 	 $validation_rules[] = array('field' => 'upro_college', 'label' => '所属学院', 'rules' => 'required|is_unique[ga_user_profiles.upro_college_id]');
	  }	 
	  else
	  {
	 	 $validation_rules[] = array('field' => 'upro_college', 'label' => '所属学院', 'rules' => 'required');
	  }	 
	 
	 }	 
	 $this->form_validation->set_rules($validation_rules);		
	 if ($this->form_validation->run())
	 {
		$u_accounts_data = array(
			'uacc_email' => $this->input->post('upro_email'),
			'uacc_group_fk' => $this->input->post('upro_group')
		);
		$u_profiles_data = array(
		  'upro_first_name' => $this->input->post('upro_first_name'),
			'upro_last_name' => $this->input->post('upro_last_name'),
			'upro_phone' => $this->input->post('upro_phone')
		);
	  if($this->input->post('upro_group')==2)
	  {
	 	 $u_profiles_data['upro_college_id'] = $this->input->post('upro_college');
	  }	 		
	  $this->db->trans_start();
    $this->db->where('uacc_id', $this->input->post('upro_id'));
    $this->db->update('user_accounts', $u_accounts_data); 	
    $this->db->where('upro_id', $this->input->post('upro_id'));	
    $this->db->update('ga_user_profiles', $u_profiles_data); 
    $this->db->trans_complete();
	$this->session->set_flashdata('message', '账户更新成功！');
    redirect('gass_auth_teachers/manage_user_accounts');
	 }
	 $this->data['message'] = validation_errors('<p class="error_msg">', '</p>');
	 return FALSE;		 	
	}		
	
 	/**
	 * 更新用户的基本信息
	 * 
	 * 主要用于个人用户更新自己的登陆、通讯信息
	 */	
  function update_person_account()
  {
	 $this->load->library('form_validation');
	 $validation_rules = array(
			array('field' => 'upro_name', 'label' => '用户名', 'rules' => 'required'),
			array('field' => 'upro_phone', 'label' => '手机号码', 'rules' => 'required')
	 );
	 //当Email信息如果被改动，则要去判断是否在当前数据库中存在这个Email信息
	 if( $this->input->post('upro_email') != $this->input->post('original_email') )
	 {
	 	$validation_rules[] = array('field' => 'upro_email', 'label' => '邮箱', 'rules' => 'required|is_unique[user_accounts.uacc_email]');
	 }	 
	 else
	 {
	 	$validation_rules[] = array('field' => 'upro_email', 'label' => '邮箱', 'rules' => 'required');
	 }	 
	 $this->form_validation->set_rules($validation_rules);		
	 if ($this->form_validation->run())
	 {
		$u_accounts_data = array(
		  'uacc_username' => $this->input->post('upro_name'),
			'uacc_email' => $this->input->post('upro_email')
		);
		$u_profiles_data = array(
			'upro_phone' => $this->input->post('upro_phone')
		);	
	  $this->db->trans_start();
    $this->db->where('uacc_id', $this->input->post('upro_id'));
    $this->db->update('user_accounts', $u_accounts_data); 	
    $this->db->where('upro_id', $this->input->post('upro_id'));	
    $this->db->update('ga_user_profiles', $u_profiles_data); 
    $this->db->trans_complete();
	$this->session->set_flashdata('message', '账户更新成功！');
    redirect('gass_users/update_user_account/'.$this->input->post('upro_id'));
	 }
	 $this->data['message'] = validation_errors('<p class="error_msg">', '</p>');
	 return FALSE;			
  }	

  /**
	 * 更新密码
	 * 
	 */
	function change_password()
	{
		$this->load->library('form_validation');
    $validation_rules = array(
			array('field' => 'upro_pass', 'label' => '当前密码', 'rules' => 'required'),
			array('field' => 'upro_new_pass', 'label' => '新密码', 'rules' => 'required|validate_password|matches[upro_con_pass]'),
			array('field' => 'upro_con_pass', 'label' => '确认密码', 'rules' => 'required')
		);		
		$this->form_validation->set_rules($validation_rules);
		if ($this->form_validation->run())
		{
			// Get password data from input.
			$identity = $this->flexi_auth->get_user_identity();
			$current_password = $this->input->post('upro_pass');
			$new_password = $this->input->post('upro_new_pass');			
			
			// Note: Changing a password will delete all 'Remember me' database sessions for the user, except their current session.
			$response = $this->flexi_auth->change_password($identity, $current_password, $new_password);
			
			$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
			redirect('gass_users/update_user_account/'.$this->flexi_auth->get_user_id());
		}
		else
		{		
			// Set validation errors.
			$this->data['message'] = validation_errors('<p class="error_msg">', '</p>');
			return FALSE;
		}
	}
	
   	/**
	 * update_user_privileges
	 * Updates the privileges for a specific user.
	 */
    function update_user_privileges($user_id)
    {
		// Update privileges.
		foreach($this->input->post('update') as $row){
			if ($row['current_status'] != $row['new_status']){
				// Insert new user privilege.
				if ($row['new_status'] == 1){
					$this->flexi_auth->insert_privilege_user($user_id, $row['id']);	
				}else{
					$sql_where = array(
						$this->flexi_auth->db_column('user_privilege_users', 'user_id') => $user_id,
						$this->flexi_auth->db_column('user_privilege_users', 'privilege_id') => $row['id']
					);
					$this->flexi_auth->delete_privilege_user($sql_where);
				}
			}
		}
		// Save any public or admin status or error messages to CI's flash session data.
		$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
		
		// Redirect user.
		redirect('gass_auth_teachers/manage_user_accounts');			
	}
   	/**
	 * update_group_privileges
	 * Updates the privileges for a specific user group.
	 */
	function update_group_privileges($group_id){
		// Update privileges.
		foreach($this->input->post('update') as $row){
			if ($row['current_status'] != $row['new_status']){
				// Insert new user privilege.
				if ($row['new_status'] == 1){
					$this->flexi_auth->insert_user_group_privilege($group_id, $row['id']);	
				}else{
					$sql_where = array(
						$this->flexi_auth->db_column('user_privilege_groups', 'group_id') => $group_id,
						$this->flexi_auth->db_column('user_privilege_groups', 'privilege_id') => $row['id']
					);
					$this->flexi_auth->delete_user_group_privilege($sql_where);
				}
			}
		}

		// Save any public or admin status or error messages to CI's flash session data.
		$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
		
		// Redirect user.
		redirect('gass_auth_teachers/manage_user_groups');			
    }	
  	/**
	 * manage_privileges
	 * The function loops through all POST data checking the 'Delete' checkboxes that have been checked, and deletes the associated privileges.
	 */
    function manage_privileges(){
        // Delete privileges.
        var_dump($this->input->post('delete_privilege'));
		if ($delete_privileges = $this->input->post('delete_privilege')){
			foreach($delete_privileges as $privilege_id => $delete){
				// Note: As the 'delete_privilege' input is a checkbox, it will only be present in the $_POST data if it has been checked,
				// therefore we don't need to check the submitted value.
				$this->flexi_auth->delete_privilege($privilege_id);
			}
		}

		// Save any public or admin status or error messages to CI's flash session data.
		$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
		// Redirect user.
		redirect('gass_auth_teachers/manage_privileges');			
	}
  	/**
	 * insert_privilege
	 * Inserts a new privilege.
	 */
	function insert_privilege()
	{
		$this->load->library('form_validation');
		$validation_rules = array(
			array('field' => 'insert_privilege_name', 'label' => '权限名称', 'rules' => 'required')
		);
		$this->form_validation->set_rules($validation_rules);
		if ($this->form_validation->run())
		{
			// Get privilege data from input.
			$privilege_name = $this->input->post('insert_privilege_name');
			$privilege_desc = $this->input->post('insert_privilege_description');

			$this->flexi_auth->insert_privilege($privilege_name, $privilege_desc);
				
			// Save any public or admin status or error messages to CI's flash session data.
			$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
			
			// Redirect user.
			redirect('gass_auth_teachers/manage_privileges');			
		}
		else
		{
			$this->data['message'] = validation_errors('<p class="error_msg">', '</p>');
			return FALSE;
		}
	}
}
